package com.kosmos.dubhe.wxcp.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import org.bouncycastle.crypto.engines.SM2Engine;

import java.security.KeyPair;
import java.util.Base64;

/**
 * @author wukai
 * @Date 2025-04-04 20:20
 */
public class Sm2Encryption {

    public static String[] genPair() {
        KeyPair keyPairGenerator = SecureUtil.generateKeyPair("SM2");
        String publicKeyString = Base64.getEncoder().encodeToString(keyPairGenerator.getPublic().getEncoded());
        String privateKeyString = Base64.getEncoder().encodeToString(keyPairGenerator.getPrivate().getEncoded());
        return new String[]{publicKeyString, privateKeyString};
    }

    public static SM2 genSm2() {
        String[] pair = genPair();
        return genSm2(pair[1], pair[0]);
    }

    public static SM2 genSm2(String publicKeyString, String privateKeyString) {
        SM2 delegate = SmUtil.sm2(privateKeyString, publicKeyString);
        delegate.setMode(SM2Engine.Mode.C1C3C2);
        return delegate;
    }


    public static String encryptToBase64(String plainText, String publicKey) throws Exception {
        return genSm2(publicKey, null).encryptBase64(plainText, KeyType.PublicKey);
    }

    public static String decryptFromBase64(String cipherText, String privateKey) throws Exception {
        return genSm2(null, privateKey).decryptStr(cipherText.replace(' ', '+'), KeyType.PrivateKey);
    }
}
